﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DailyComics.Common.Model.CachingStrategies
{
  public class CompositeCacheStrategy : ICachingStrategy
  {
    private List<ICachingStrategy> caches;

    public CompositeCacheStrategy()
    {
      caches = new List<ICachingStrategy>();
    }

    public void AddCache(ICachingStrategy strategy)
    {
      if(strategy != null || !caches.Contains(strategy)) caches.Add(strategy);
    }

    #region ICachingStrategy Members

    public void Add(DateTime date, byte[] image)
    {
      caches.ForEach(c => c.Add(date, image));
    }

    public byte[] Get(DateTime date)
    {
      try
      {
        var image = caches.FirstOrDefault(c => c.Contains(date)).Get(date);

        Add(date, image);

        return image;
      }
      catch (Exception)
      {
        return null;
      }    
    }

    public bool Contains(DateTime date)
    {
      return caches.Any(c => c.Contains(date));
    }

    public void Clear()
    {
      caches.ForEach(c => c.Clear());
    }

    #endregion
  }
}
